#!/usr/bin/env python

import sys
import database
import ConfigParser

from smtplib import SMTP

try:    # 2.5 compatibility
  from smtplib import SMTP_SSL
except ImportError:
  pass

from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr

config = ConfigParser.ConfigParser()
config.readfp(open('config.ini'))

libraryName = config.get('library', 'name')
libraryString = ('the %s' % libraryName) if not libraryName.lower().startswith('the ') else libraryName

# Read SMTP configuration
try:
  server = config.get('backend', 'smtp_server')
except ConfigParser.NoOptionError:
  server = None

if server:
  try:
    port = int(config.get('backend', 'smtp_port'))
  except ConfigParser.NoOptionError:
    port = None

  try:
    useSSL = bool(int(config.get('backend', 'smtp_ssl')))
  except ConfigParser.NoOptionError:
    useSSL = False
  
  try:
    useTLS = bool(int(config.get('backend', 'smtp_tls')))
  except ConfigParser.NoOptionError:
    useTLS = False
  
  try:
    username = config.get('backend', 'smtp_username')
  except ConfigParser.NoOptionError:
    username = ''
  
  try:
    password = config.get('backend', 'smtp_password')
  except ConfigParser.NoOptionError:
    password = ''
else:
  port = None
  useSSL = False

try:
  serverEmail = '%s <%s>' % (libraryName, config.get('backend', 'server_email'))
except ConfigParser.NoOptionError:
  print 'Error: You must specify a value for server_email in your configuration file!'
  sys.exit(1)
  
def send_email(sender, recipient, subject, body):
  '''
  This code was borrowed from http://mg.pov.lt/blog/unicode-emails-in-python.html
  Many thanks to Marius Gedminas for posting this code.
  
  Send an email.

  All arguments should be Unicode strings (plain ASCII works as well).

  Only the real name part of sender and recipient addresses may contain
  non-ASCII characters.

  The email will be properly MIME encoded and delivered though SMTP to
  localhost port 25.  This is easy to change if you want something different.

  The charset of the email will be the first one out of US-ASCII, ISO-8859-1
  and UTF-8 that can represent all the characters occurring in the email.
  '''
  # Header class is smart enough to try US-ASCII, then the charset we
  # provide, then fall back to UTF-8.
  header_charset = 'ISO-8859-1'
  
  # We must choose the body charset manually
  for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
    try:
      body.encode(body_charset)
    except UnicodeError:
      pass
    else:
      break

  # Split real name (which is optional) and email address parts
  sender_name, sender_addr = parseaddr(sender)
  recipient_name, recipient_addr = parseaddr(recipient)
  
  # We must always pass Unicode strings to Header, otherwise it will
  # use RFC 2047 encoding even on plain ASCII strings.
  sender_name = str(Header(unicode(sender_name), header_charset))
  recipient_name = str(Header(unicode(recipient_name), header_charset))
  
  # Make sure email addresses do not contain non-ASCII characters
  sender_addr = sender_addr.encode('ascii')
  recipient_addr = recipient_addr.encode('ascii')
  
  # Create the message ('plain' stands for Content-Type: text/plain)
  msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
  msg['From'] = formataddr((sender_name, sender_addr))
  msg['To'] = formataddr((recipient_name, recipient_addr))
  msg['Subject'] = Header(unicode(subject), header_charset)
  
  # Send the message via SMTP to localhost:25
  smtp = SMTP_SSL(server, port) if useSSL else SMTP(server, port)
  smtp.ehlo()
  if useTLS:
    smtp.starttls()
  if username:
    smtp.login(username, password)
  smtp.sendmail(sender, recipient, msg.as_string())
  smtp.quit()
  
# Fetch the list of overdue books
overdue = database.getCheckedOutResources(user_id=None, overdue=True)
records = {}

# Sort the overdue resources by email address
for record in overdue:
  email = record['card_email']
  
  if email:
    if email not in records:
      records[email] = []
      
    records[email].append(record)
  
# Send the individual emails
for email in records:
  overdueResources = records[email]
  
  name = overdueResources[0]['card_name']
  header = u'%s %s' % ('Title'.ljust(120), 'Due Date')
  body = '\n'.join([u'%s %s' % (resource['title'][:120].ljust(120), resource['due_date'].date())
                    for resource in overdueResources])
  message = u'%s,\n\nThis is an automated message from %s to let you know that you have some overdue resources.\n\n%s\n%s' % (name, libraryString, header, body)
  
  send_email(serverEmail, email, 'Overdue notice', message)